
#include "DogFightBehaviour.h"
#include "CommonBehaviours.h"
#include "../Ship.h"

#include <cassert>
#include <cmath>

#define INTERCEPT_DIST 5.0f
#define FLOAT_FIRE_DIST 1.5f


DogFightBehaviour::DogFightBehaviour(Ship *my_ship) :
    my_ship(my_ship) {

    assert(my_ship != NULL);
}


DogFightBehaviour::~DogFightBehaviour(){

}


bool DogFightBehaviour::shouldIAttack(Ship *target_ship){
    return (my_ship->getPosition() - target_ship->getPosition()).length() < INTERCEPT_DIST &&
           CommonBehaviours::canSeePoint(my_ship, target_ship->getPosition());
}


bool DogFightBehaviour::attackTarget(Ship *target_ship){
    float ship_dist = (target_ship->getPosition()-my_ship->getPosition()).length();

    if(ship_dist > INTERCEPT_DIST){
        return false; // too far to dog fight.
    }
    else if(ship_dist > FLOAT_FIRE_DIST){
        interceptTarget(target_ship); // far enough that we should try to get closer
    }
    else{
        floatFire(target_ship); // close enough that thrusters arent needed, careful aim
    }

    return true;
}


void DogFightBehaviour::interceptTarget(Ship *target){
    CommonBehaviours::goDirectToPoint(my_ship, target->getPosition());
    
    Vector2D to_ship = target->getPosition() - my_ship->getPosition();
    if(to_ship.length() < target->getSize()*2.0f){ return; }
    to_ship.normalise();

    float angle_diff = acosf(to_ship.dotProduct(my_ship->getHeading())) * 180.0f/M_PI;
    if(fabs(angle_diff) < 10.0f){
        my_ship->fire();
    }
}


void DogFightBehaviour::floatFire(Ship *target){
    Vector2D to_ship = target->getPosition() - my_ship->getPosition();
    if(to_ship.length() < target->getSize()*2.0f){ return; }
    to_ship.normalise();

    float h_angle = acosf(to_ship.dotProduct(my_ship->getHeading())) * 180.0f/M_PI;
    if(h_angle != h_angle){ 
        h_angle = 0.0f;
    }

    to_ship.rotate(-my_ship->getRotation());
    if(to_ship.x < 0.0f){ my_ship->turn(h_angle); }
    else { my_ship->turn(-h_angle); }

    if(fabs(h_angle) < 5.0f){
        my_ship->fire();
    }

}


